package com.aurora.source.authority.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aurora.source.R;
import com.aurora.source.authority.adapter.ProcessAuthSelectAdapter;
import com.aurora.source.authority.adapter.SysAuthSelectAdapter;
import com.aurora.source.authority.bean.ProcessDataBean;
import com.aurora.source.authority.bean.SysAuthDataBean;
import com.aurora.source.authority.presenter.PersonAuthAddPresenter;
import com.aurora.source.authority.view.IPersonAuthAddView;
import com.aurora.source.base.BaseWhiteToolbarActivity;
import com.aurora.source.util.DpPxUtil;
import com.aurora.source.util.ErrorImgUtil;
import com.aurora.source.util.SPUtils;
import com.aurora.source.util.Validator;
import com.aurora.source.widget.CustomRecyclerView;
import com.aurora.source.widget.flowlayout.FlowLayoutManager;
import com.aurora.source.widget.flowlayout.SpaceItemDecoration;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.wildma.idcardcamera.camera.CameraActivity;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author: ww
 * @description: 添加人员授权
 * @date: 2018/9/11
 */
public class PersonAuthAddActivity extends BaseWhiteToolbarActivity<PersonAuthAddPresenter> implements IPersonAuthAddView {
    private static final int GET_AUTH = 11111;
    @BindView(R.id.tv_select_auth)
    TextView tvSelectAuth;
    @BindView(R.id.bt_sure)
    AppCompatButton btSure;
    @BindView(R.id.ll_IDcard_front)
    LinearLayout llIDcardFront;
    @BindView(R.id.ll_IDcard_tail)
    LinearLayout llIDcardTail;
    @BindView(R.id.et_number)
    EditText etNumber;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.et_confirm_password)
    EditText etConfirmPassword;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_ID_number)
    EditText etIDNumber;
    @BindView(R.id.iv_card_just)
    ImageView ivCardJust;
    @BindView(R.id.iv_card_against)
    ImageView ivCardAgainst;
    File cardJust;
    File cardAgainst;
    int cardType;//0正面1反面
    @BindView(R.id.rv_auth_data)
    RecyclerView rvAuthData;
    @BindView(R.id.rv_sys_auth_data)
    CustomRecyclerView rvSysAuthData;
    private ProcessAuthSelectAdapter processAuthSelectAdapter;
    private SysAuthSelectAdapter sysAuthSelectAdapter;

    @Override
    public PersonAuthAddPresenter attach() {
        return new PersonAuthAddPresenter(this);
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_person_auth_add;
    }

    @Override
    public void initData(@Nullable Bundle bundle) {

    }

    @Override
    public void initView(Bundle savedInstanceState, View contentView) {
        simpleToolbar.setMainTitle("权限管理");
        simpleToolbar.setLeftVisibility(View.VISIBLE);

        processAuthSelectAdapter = new ProcessAuthSelectAdapter();
        sysAuthSelectAdapter = new SysAuthSelectAdapter();

        rvAuthData.setLayoutManager(new FlowLayoutManager());
        rvAuthData.setAdapter(processAuthSelectAdapter);
        rvAuthData.addItemDecoration(new SpaceItemDecoration(DpPxUtil.dp2px(this, 5)));

        rvSysAuthData.setLayoutManager(new FlowLayoutManager());
        rvSysAuthData.setAdapter(sysAuthSelectAdapter);
        rvSysAuthData.addItemDecoration(new SpaceItemDecoration(DpPxUtil.dp2px(this, 5)));


    }

    @Override
    public void doBusiness() {

    }

    /**
     * 获取ids
     *
     * @return
     */
    private String getProcessIds() {
        List<ProcessDataBean.ProcessListBean> dataList = processAuthSelectAdapter.getDataList();
        StringBuilder processIds = new StringBuilder();
        if (dataList == null || dataList.size() == 0) {
            return processIds.toString();
        } else {
            for (int i = 0; i < dataList.size(); i++) {
                if (dataList.get(i).isSelect()) {
                    processIds.append(dataList.get(i).getProcessId()).append(",");
                }
            }
            if(processIds.length()>0){
                processIds.deleteCharAt(processIds.length() - 1);
            }
            return processIds.toString();
        }
    }

    @OnClick({R.id.tv_select_auth, R.id.bt_sure, R.id.ll_IDcard_front, R.id.ll_IDcard_tail})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_select_auth:
                startActivityForResult(new Intent(this, AddJurisdictionActivity.class), GET_AUTH);
                //     gotoActivity(SelectAuthActivity.class, false);
                break;
            case R.id.bt_sure:
                if (checkNull()) {
                    return;
                }

                Map<String, String> params = new HashMap<>();
                params.put("parentUserId", (String) SPUtils.get(activity, SPUtils.USER_ID, ""));
                params.put("userAccount", etNumber.getText().toString());
                params.put("userName", etName.getText().toString());
                params.put("userPwd", etPassword.getText().toString());
                params.put("userMobile", etPhone.getText().toString());
                params.put("idCardNo", etIDNumber.getText().toString());
                params.put("processIds", getProcessIds());
                params.put("sysRoleCodes",getSysRoleCodes());
                basePresenter.affirmAdd(activity, params, cardJust, cardAgainst);
                break;
            case R.id.ll_IDcard_front:
                cardType = 0;
                CameraActivity.toCameraActivity(this, CameraActivity.TYPE_IDCARD_FRONT);
                // showPictureSelector();
                break;
            case R.id.ll_IDcard_tail:
                cardType = 1;
                CameraActivity.toCameraActivity(this, CameraActivity.TYPE_IDCARD_BACK);

                //  showPictureSelector();
                break;
        }
    }

    //
    private String getSysRoleCodes() {
        List<SysAuthDataBean.SystemRoleDTOListBean> dataList = sysAuthSelectAdapter.getDataList();
        StringBuilder processIds = new StringBuilder();
        if (dataList == null || dataList.size() == 0) {
            return processIds.toString();
        } else {
            for (int i = 0; i < dataList.size(); i++) {
                if (dataList.get(i).isSelect()) {
                    processIds.append(dataList.get(i).getSysRoleCode()).append(",");
                }
            }
            if(processIds.length()>0){
                processIds.deleteCharAt(processIds.length() - 1);
            }
            return processIds.toString();
        }
    }

    /**
     * 提交校验
     */
    private boolean checkNull() {
        if (!etPassword.getText().toString().equals(etConfirmPassword.getText().toString())) {
            showToast("密码不一致");
            return true;
        }

        if (!Validator.isPasswordStrong(etPassword.getText().toString())) {
            showToast("密码为6~20位数字，字母组合");
            return true;
        }

        if (!Validator.isMobile(etPhone.getText().toString())) {
            showToast("手机号格式不正确");
            return true;
        }

        if (!Validator.isIDCard(etIDNumber.getText().toString())) {
            showToast("身份证格式不正确");
            return true;
        }

        return false;
    }

    //添加图片
    public void showPictureSelector() {
        try {
            PictureSelector.create(activity)
                    .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .maxSelectNum(1)// 最大图片选择数量 int
                    .minSelectNum(1)// 最小选择数量 int
                    .imageSpanCount(4)// 每行显示个数 int
                    .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                    .isCamera(true)// 是否显示拍照按钮 true or false
                    .imageFormat(PictureMimeType.JPEG)// 拍照保存图片格式后缀,默认jpeg
                    .setOutputCameraPath(application.getFilesDir().getAbsolutePath())// 自定义拍照保存路径,可不填
                    .enableCrop(true)// 是否裁剪 true or false
                    .compress(true)// 是否压缩 true or false
                    .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示 true or false
                    .compressSavePath(application.getFilesDir().getAbsolutePath())//压缩图片保存地址
                    .freeStyleCropEnabled(true)// 裁剪框是否可拖拽 true or false
                    .circleDimmedLayer(false)// 是否圆形裁剪 true or false
                    .openClickSound(true)// 是否开启点击声音 true or false
                    .cropCompressQuality(80)// 裁剪压缩质量 默认90 int
                    .minimumCompressSize(100)// 小于100kb的图片不压缩
                    .synOrAsy(true)//同步true或异步false 压缩 默认同步
                    .scaleEnabled(true)// 裁剪是否可放大缩小图片 true or false
                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CameraActivity.REQUEST_CODE && resultCode == CameraActivity.RESULT_CODE) { //身份证
            //获取图片路径，显示图片
            final String path = CameraActivity.getImagePath(data);
            if (cardType == 0) {
                cardJust = new File(path);
                Glide.with(this)
                        .load(cardJust)
                        .apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE).skipMemoryCache(true).error(ErrorImgUtil.getErrorImgRandom()))
                        .into(ivCardJust);
            } else {
                cardAgainst = new File(path);
                Glide.with(this)
                        .load(cardAgainst)
                        .apply(new RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE).skipMemoryCache(true).error(ErrorImgUtil.getErrorImgRandom()))
                        .into(ivCardAgainst);
            }
        } else if (requestCode == GET_AUTH) {//添加权限
            if (resultCode == RESULT_OK) {
                List<ProcessDataBean.ProcessListBean> dataList1 = (List<ProcessDataBean.ProcessListBean>) data.getSerializableExtra("data1");
                processAuthSelectAdapter.setDataList(dataList1);
                List<SysAuthDataBean.SystemRoleDTOListBean> dataList2 = (List<SysAuthDataBean.SystemRoleDTOListBean>) data.getSerializableExtra("data2");
                sysAuthSelectAdapter.setDataList(dataList2);

            }
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void onPersonAuthAddSuccess(String data) {
        showToast(data);
        hideSoftInput();
        finish();
    }


    @Override
    public void onPersonAuthAddFail(String msg) {
        showToast(msg);
    }
}
